//
//  HJInviteSelectVisitationVC.m
//  Keping
//
//  Created by apple on 2017/11/8.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "HJInviteSelectVisitationVC.h"

typedef NS_ENUM(NSInteger, HJSelectvisitationType) {
    HJSelectvisitationTypeNonaml = 0,
    HJSelectvisitationTypeHistory,
    HJSelectvisitationTypeEntity,
    HJSelectvisitationTypeFriend
};

@interface HJInviteSelectVisitationVC ()<UITableViewDelegate, UITableViewDataSource, HJSelectDateViewDelegate>

/**tableView*/
@property(nonatomic,weak)UITableView*tableView;
/**数据源*/
@property(nonatomic,strong)NSMutableArray*dataAry;
/**拜访历史好友列表*/
@property (nonatomic, copy) NSArray<VisitEntityViews *> *historyModels;
/**邀请好友历史列表*/
@property (nonatomic, copy) NSArray<HJAppointmentModel *> *entityModels;
/**获取好友*/
@property (nonatomic, copy) NSArray<RelationFriendViews *> *friendModels;
/**拜访历史好友列表*/
@property (nonatomic, strong) NSMutableArray *previousGuests;
/**邀请好友列表*/
@property (nonatomic, strong) NSMutableArray *previousVisitors;
/**我的好友列表*/
@property (nonatomic, strong) NSMutableArray *previousFriends;
/***/
@property (nonatomic, assign) HJSelectvisitationType visitationType;

@end

@implementation HJInviteSelectVisitationVC

-(NSMutableArray *)dataAry
{
    if (!_dataAry) {
        // 0 : 客人  1 : 游客  2 : 朋友
        VisitEntityViews *history = [[VisitEntityViews alloc] init];
        history.fullName = @"Choose from Previous Guest Lists";
        
        VisitEntityViews *entity = [[VisitEntityViews alloc] init];
        entity.fullName = @"Choose from Previous Visitors";
        
        RelationFriendViews *friend = [[RelationFriendViews alloc] init];
        friend.nickName  = @"Choose from Friends";
        
        _dataAry = [[NSMutableArray alloc] initWithObjects:@[history], @[entity], @[friend], nil];
    }
    return _dataAry;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.visitationType = HJSelectvisitationTypeNonaml;
    [self setUI];
    [self getData];
}
-(void)setUI
{
    self.navigationItem.title=@"Select Visitors";
    UITableView*tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.backgroundColor=[UIColor colorWithHexString:@"#f2f1f6"];
    [self.view addSubview:tableView];
    self.tableView=tableView;
    
    //添加table尾部
    UIView*footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, K_FactorH(80))];
    tableView.tableFooterView=footerView;
    footerView.backgroundColor=[UIColor clearColor];
    CGFloat margin =K_FactorW(20);
    UIButton*addBtn=[[UIButton alloc]initWithFrame:CGRectMake(margin, K_FactorH(30), footerView.width-2*margin, footerView.height-K_FactorH(30))];
    [footerView addSubview:addBtn];
    addBtn.layer.cornerRadius=addBtn.height/2;
    addBtn.layer.masksToBounds=YES;
    [addBtn setBackgroundColor:[UIColor colorWithHexString:@"#6853fa"] forState:UIControlStateNormal];
    [addBtn setTitle:@"Send Invitation" forState:UIControlStateNormal];
    addBtn.titleLabel.font=[UIFont boldSystemFontOfSize:20];
    [addBtn addTarget:self action:@selector(clickNextStep) forControlEvents:UIControlEventTouchUpInside];
}

- (void)getData {
    [super getData];
    [self showLoading];
    //拜访历史好友列表
    __block HJInviteSelectVisitationRequest *visitation = [[HJInviteSelectVisitationRequest alloc] init];
    //邀请好友历史列表
    __block HJInviteInviteEntityItemsnRequest   *entity = [[HJInviteInviteEntityItemsnRequest alloc] init];
    //获取好友
    __block HJRelationFriendsRequest *friend = [[HJRelationFriendsRequest alloc] initWithIsBlock:@""];
    KBatchRequest *request = [[KBatchRequest alloc] initWithRequestArray:@[visitation, entity, friend]];
    WEAKSELF
    [request startWithCompletionBlockWithSuccess:^(KBatchRequest * _Nonnull batchRequest) {
        [weakSelf hideHUD];
        HJInviteSelectVisitationHistoryModel *history1 = [HJInviteSelectVisitationHistoryModel modelWithJSON:visitation.responseData];
        HJInviteInviteEntityItemsnModel      *history2 = [HJInviteInviteEntityItemsnModel modelWithJSON:entity.responseData];
        HJVisitFriendModel *history3 = [HJVisitFriendModel modelWithJSON:friend.responseData];
        
        if (history1.statusCode == 200) {
            weakSelf.historyModels = history1.visitEntityViews;
        } else {
            [weakSelf showError:batchRequest.requestArray[0].error];
        }
        
        if (history2.statusCode == 200) {
            weakSelf.entityModels  = history2.inviteEntityItemViews;
        } else {
            [weakSelf showError:batchRequest.requestArray[1].error];
        }
        
        if (history3.statusCode == 200) {
            weakSelf.friendModels = history3.relationFriendViews;
        } else {
            [weakSelf showError:batchRequest.requestArray[2].error];
        }
    } failure:^(KBatchRequest * _Nonnull batchRequest) {
        [weakSelf showError:batchRequest.failedRequest.error];
    }];
}

- (void)addData {
    WEAKSELF
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        if (self.previousVisitors.count > 0) {
            NSMutableArray *visitors = [NSMutableArray new];
            for (int i = 0; i < self.previousVisitors.count; i++) {
                VisitEntityViews *entity = [self.previousVisitors objectAtIndex:i];
                HJVisitFriendAddRequest *visitation = [[HJVisitFriendAddRequest alloc] init];
                visitation.params = @{
                                      @"email":entity.email,
                                      @"fullName":entity.fullName,
                                      @"inviteId":self.inviteEntityID,
                                      @"message":entity.message,
                                      @"phone":entity.phone,
                                      @"vehicleNumber":entity.vehicleNumber
                                      };
                [visitors addObject:visitation];
            }
            KBatchRequest *batch1 = [[KBatchRequest alloc] initWithRequestArray:@[visitors.copy]];
            [batch1 startWithCompletionBlockWithSuccess:^(KBatchRequest * _Nonnull batchRequest) {
                
                for (int x = 0; x < batchRequest.requestArray.count; x++) {
                    NSDictionary *dict = [batchRequest.requestArray[x] responseObject];
                    NSInteger statusCode = [[dict objectForKey:@"statusCode"] integerValue];
                    if (statusCode != 200) {
                        KLog(@"添加拜访好友出错:%@",[dict objectForKey:@"msg"]);
                    }
                }
            } failure:^(KBatchRequest * _Nonnull batchRequest) {
                KLog(@"添加拜访好友出错:%@",batchRequest);
            }];
        }
    });
    dispatch_group_async(group, queue, ^{
        if (weakSelf.previousGuests.count > 0) {
            NSMutableArray *visitors = [NSMutableArray new];
            for (int i = 0; i < weakSelf.previousGuests.count; i++) {
                VisitEntityViews *entity = [weakSelf.previousGuests objectAtIndex:i];
                HJVisitFriendAddRequest *visitation = [[HJVisitFriendAddRequest alloc] init];
                visitation.params = @{
                                      @"email":entity.email,
                                      @"fullName":entity.fullName,
                                      @"inviteId":self.inviteEntityID,
                                      @"message":entity.message,
                                      @"phone":entity.phone,
                                      @"vehicleNumber":entity.vehicleNumber
                                      };
                [visitors addObject:visitation];
            }
            KBatchRequest *batch1 = [[KBatchRequest alloc] initWithRequestArray:@[visitors.copy]];
            [batch1 startWithCompletionBlockWithSuccess:^(KBatchRequest * _Nonnull batchRequest) {
                
                for (int x = 0; x < batchRequest.requestArray.count; x++) {
                    NSDictionary *dict = [batchRequest.requestArray[x] responseObject];
                    NSInteger statusCode = [[dict objectForKey:@"statusCode"] integerValue];
                    if (statusCode != 200) {
                        KLog(@"添加拜访好友出错:%@",[dict objectForKey:@"msg"]);
                    }
                }
            } failure:^(KBatchRequest * _Nonnull batchRequest) {
                KLog(@"添加拜访好友出错:%@",batchRequest);
            }];
        }
    });
    dispatch_group_async(group, queue, ^{
        if (weakSelf.previousFriends.count > 0) {
            NSMutableArray *visitors = [NSMutableArray new];
            for (int i = 0; i < weakSelf.previousFriends.count; i++) {
                RelationFriendViews *entity = [weakSelf.previousFriends objectAtIndex:i];
                HJVisitFriendAddRequest *visitation = [[HJVisitFriendAddRequest alloc] init];
                visitation.params = @{
                                      @"email":@"",
                                      @"fullName":entity.nickName,
                                      @"inviteId":weakSelf.inviteEntityID,
                                      @"message":@"",
                                      @"phone":entity.phone,
                                      @"vehicleNumber":@""
                                      };
                [visitors addObject:visitation];
            }
            KBatchRequest *batch1 = [[KBatchRequest alloc] initWithRequestArray:@[visitors.copy]];
            [batch1 startWithCompletionBlockWithSuccess:^(KBatchRequest * _Nonnull batchRequest) {
                
                for (int x = 0; x < batchRequest.requestArray.count; x++) {
                    NSDictionary *dict = [batchRequest.requestArray[x] responseObject];
                    NSInteger statusCode = [[dict objectForKey:@"statusCode"] integerValue];
                    if (statusCode != 200) {
                        KLog(@"添加拜访好友出错:%@",[dict objectForKey:@"msg"]);
                    }
                }
            } failure:^(KBatchRequest * _Nonnull batchRequest) {
                KLog(@"添加拜访好友出错:%@",batchRequest);
            }];
        }
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [weakSelf showSuccess:@"Invitation Sent!"];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    });
}

- (void)clickNextStep {
    [self addData];
}

#pragma mark --UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataAry.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataAry[section] count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HJVisitFriendViewCell*cell=[HJVisitFriendViewCell cellWithTableView:tableView];
    if (indexPath.row == 0) {
        cell.isNomarl = NO;
    } else {
        cell.isNomarl = YES;
    }
    id friend = self.dataAry[indexPath.section][indexPath.row];
    if ([friend isKindOfClass:[VisitEntityViews class]]) {
        VisitEntityViews *entity = friend;
        cell.title = entity.fullName;
    } else if ([friend isKindOfClass:[HJAppointmentModel class]]){
        HJAppointmentModel *model = friend;
        cell.title = model.fullName;
    } else {
        RelationFriendViews *entity = friend;
        cell.title = entity.nickName;
    }
    cell.isEdit = NO;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row     = indexPath.row;
    HJVisitFriendViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isSelect = !cell.isSelect;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (row == 0) {
        NSMutableArray *array = [self.dataAry[section] mutableCopy];
        if (array.count == 1) {
            if (section == 0) {
                [array addObjectsFromArray:self.entityModels];
            } else if (section ==1) {
                [array addObjectsFromArray:self.historyModels];
            } else {
                [array addObjectsFromArray:self.friendModels];
            }
            [self.dataAry replaceObjectAtIndex:section withObject:array];
            [tableView reloadSection:section withRowAnimation:UITableViewRowAnimationNone];
        } else {
            id obj = [self.dataAry[section] firstObject];
            [self.dataAry[section] removeAllObjects];
            [self.dataAry[section] addObject:obj];
            [tableView reloadSection:section withRowAnimation:UITableViewRowAnimationNone];
            
        }
    } else {
        id remObj = self.dataAry[section][row];
        if (cell.isSelect) {
            if (section == 0) {
                [self.previousGuests removeObject:remObj];
            } else if (section == 1) {
                [self.previousVisitors removeObject:remObj];
            } else {
                [self.previousFriends removeObject:remObj];
            }
        } else {
            if (section == 0) {
                [self.previousGuests addObject:self.dataAry[section][row]];
            } else if (section == 1) {
                [self.previousVisitors addObject:self.dataAry[section][row]];
            } else {
                [self.previousFriends addObject:self.dataAry[section][row]];
            }
        }
    }
}
-(void)creatDatePicker:(UIDatePickerMode)dateModel
{
    HJSelectDateView*dateView=[[HJSelectDateView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height)];
    dateView.delegate=self;
    dateView.DateModel=dateModel;
    [self.navigationController.view addSubview:dateView];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_FactorH(60);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return K_FactorH(10);
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}

#pragma mark -- HJSelectDateViewDelegate
-(void)selectDateView:(HJSelectDateView*)selectDateView clickSelectDate:(NSString*)dateStr indexPath:(NSIndexPath*)indexPath {
    NSMutableArray *arr = [self.dataAry[1] mutableCopy];
    if (selectDateView.DateModel == UIDatePickerModeDate) {
        [arr replaceObjectAtIndex:0 withObject:dateStr];
    } else {
        [arr replaceObjectAtIndex:1 withObject:dateStr];
    }
    [self.dataAry replaceObjectAtIndex:1 withObject:arr];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
